<template>
    <div>
        <div style="padding: 10px;">

            <!--            搜索区域-->
            <div style="margin:10px 0;">
                <el-input v-model="search" placeholder="请输入关键字" style="width: 20%;" clearable/>
                <el-button type="primary" style="margin-left: 5px;" @click="find"> 查询</el-button>
                <el-button type="primary" style="margin-left: 5px;" @click="add"> 添加</el-button>
                <el-upload :action="'http://' + serverIp + ':9090/selectCourse/import'"
                           :show-file-list="false"
                           accept=".xlsx"
                           :on-error="handleExcelImportError"
                           :on-success="handleExcelImportSuccess" style="display: inline-block">
                    <el-button type="primary" class="ml-5">导入 <i class="el-icon-bottom"></i></el-button>
                </el-upload>
                <el-button type="primary" @click="exp" class="ml-5">导出 <i class="el-icon-top"></i></el-button>
            </div>
            <el-table
                    :data="tableData"
                    style="width: 100%;"
                    stripe
            >
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="id" label="ID" width="80"></el-table-column>
                <el-table-column prop="studentId" label="学生账号" width="200"></el-table-column>
                <el-table-column prop="studentName" label="姓名" width="140"></el-table-column>
                <el-table-column prop="courseId" label="课程id"></el-table-column>
                <el-table-column prop="courseName" label="课程名称"></el-table-column>
<!--                <el-table-column prop="score" label="课程学分"></el-table-column>-->
                <!--操作-->
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
                        ><i class="el-icon-edit-outline"></i> 编辑
                        </el-button>

                        <el-popconfirm
                                class="ml-5"
                                confirm-button-text='确定'
                                cancel-button-text='我再想想'
                                icon="el-icon-info"
                                icon-color="red"
                                title="您确定删除吗？"
                                @confirm="handleDelete(scope.$index,scope.row)"
                        >
                            <el-button type="danger" size="small" slot="reference"><i
                                    class="el-icon-remove-outline"></i> 删除
                            </el-button>
                        </el-popconfirm>

                    </template>
                </el-table-column>
            </el-table>
            <!--            分页栏-->
            <div style="margin: 10px 0;">
                <el-pagination
                        v-model:pageNum="pageNum"
                        :page-sizes="[5, 10, 20]"
                        :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                >
                </el-pagination>

                <!--添加与修改的表单-->
                <el-dialog title="添加选课信息" :visible.sync="dialogVisible" width="30%" >
                    <el-form label-width="80px" size="small" :rules="rules" :model="form" ref="form">
                        <el-form-item label="ID" style="display: none">
                            <el-input v-model="form.id" autocomplete="off" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="学生账号" prop="studentId" ref="studentId">
                            <el-input v-model="form.studentId" autocomplete="off"></el-input>
                        </el-form-item>
<!--                        <el-form-item label="课程ID"  prop="courseId" ref="courseId">-->
<!--                            <el-input v-model="form.courseId" :disabled="true" autocomplete="off"></el-input>-->
<!--                        </el-form-item>-->
                        <el-form-item label="课程名称" prop="courseId" ref="courseId">
                            <el-select clearable filterable v-model="form.courseId" placeholder="请选择课程名">
                                <el-option v-for="item in course" :key="item.courseId" :label="item.courseName"
                                           :value="item.courseId"></el-option>
                            </el-select>
                        </el-form-item>
<!--                        <el-form-item label="课程学分" prop="score" ref="score">-->
<!--                            <el-input-number v-model="form.score" :precision="0" :step="0.5" :min="1"-->
<!--                                             :max="100"-->
<!--                            ></el-input-number>-->
<!--                        </el-form-item>-->
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
                    </div>
                </el-dialog>
            </div>

        </div>
    </div>
</template>

<script>

    import request from "../utils/request";
    import {serverIp} from "../../public/config";
    export default {
        name: 'SelectCourse',
        components: {},
        data() {
            return {
                form: {},
                roles: {},
                serverIp: serverIp,
                dialogVisible: false,
                search: '',
                pageSize: 5,
                pageNum: 1,
                total: 20,
                tableData: [],
                course: [],
                status: [{name: "启用", value: "1"}, {name: "禁用", value: "0"}],
                rules: {
                    studentId: [
                        {required: true, message: '请输入学号', trigger: 'blur'},
                        {min: 13, max: 13, message: '请输入13个字符', trigger: 'blur'},
                    ],
                    courseId: [
                        {required: true, message: '请选择课程名称', trigger: 'change'},
                    ],
                    score: [
                        {required: true, message: '请输入学分', trigger: 'blur'},
                    ],
                }
            }
        },
        created() {
            this.load();
            this.getCourse();
        },
        methods: {
            load() {
                var mess = this;
                request.get("/selectCourse", {
                    params: {
                        pageNum: this.pageNum,
                        pageSize: this.pageSize,
                        selectCourseName: this.search,
                    }
                }).then(res => {
                    console.log("res:", res);
                    this.tableData = res.data.records;
                    this.total = res.data.total;
                })
            },
            find(){
                this.pageNum = 1;
                this.load();
            },
            add() {
                this.dialogVisible = true;
                this.form = {};
            },
            submitForm(formName) {
                let mess = this;
                this.$refs[formName].validate((valid,object) => {
                    if (valid) {
                        this.save();//提交保存
                    } else {
                        mess.locate(valid,object);
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            save() {
                console.log("form:", this.form)
                if (this.form.id) { // 更新
                    request.post('/selectCourse/save', this.form).then(res => {
                        console.log("code:", res.code)
                        if (res.code == '200') {
                            this.$message.success("保存成功")
                        } else {
                            this.$message.error("保存失败")
                        }
                        this.load() //刷新表格
                        this.dialogVisible = false
                        console.log("success")
                    })
                } else { //新增
                    request.post("/selectCourse/save", this.form).then(res => {
                        console.log(res.data)
                        if (res.code == '200') {
                            this.$message.success("添加成功")
                        } else {
                            this.$message.error("添加失败")
                        }
                        this.load() //刷新表格
                        this.dialogVisible = false
                        console.log("success")
                    })
                }

            },
            handleEdit(index, row) {
                this.form = JSON.parse(JSON.stringify(row))
                this.dialogVisible = true
                console.log(row)
            },
            handleDelete(index, row) {
                console.log(row.id)
                //注意url/{路径}/
                this.request.delete("/selectCourse/delete/" + row.id).then(res => {
                    console.log(res)
                    if (res.data === true) {
                        this.$message.success("删除成功")
                        this.load()
                    } else {
                        this.$message.error("删除失败")
                    }
                })

            },
            handleSizeChange(pageSize) { //改变当前每页的个数触发
                this.pageSize = pageSize
                console.log(pageSize)
                this.load()
            },
            handleCurrentChange(pageNum) {  //改变当前页码触发
                this.pageNum = pageNum
                this.load()
            },
            exp() {
                window.open(`http://${serverIp}:9090/selectCourse/export`)
            },
            handleExcelImportSuccess() {
                this.$message.success("导入成功")
                this.load()
            },
            handleExcelImportError() {
                this.$message.success("导入失败")
            },
            getCourse() {
                //请求课程信息数据
                request.get("/course/findAll").then(res => {
                    console.log("res:", res);
                    this.course = res.data
                })
            },
            locate(valid,object){
                let split = ''
                for (let i in object) {
                    let dom = this.$refs[i]
                    if (Object.prototype.toString.call(dom) !== '[object Object]') {
                        //这里是针对遍历的情况（多个输入框），取值为数组
                        dom = dom[0]
                        // 第一个未填写必填项的表单被记录，这个是为了处理如何把校验未成功的第一个面板展开
                        split = dom.prop
                        let index = split.indexOf('.')
                        let last = split.lastIndexOf('.')
                        // 通过未填写的表单索引展开折叠面板
                        this.activeName = Number(split.slice(index + 1, last))
                        console.log(split)
                        break
                    }
                    console.log(dom.$el)
                    dom.$el.scrollIntoView({
                        //滚动到指定节点
                        block: 'start', //值有start,center,end，nearest，当前显示在视图区域中间
                        behavior: 'instant' //值有auto、instant,smooth，缓动动画（当前是慢速的）
                    })
                    return false
                }
            },


        }

    }
</script>
